<template>
  <div class="main-view">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载企业信息...</p>
    </div>

    <!-- 管理员页面 -->
    <div v-else-if="isAdmin" class="admin-content">
      <h1>平台管理员控制台</h1>
      <p>欢迎回来，尊敬的平台管理员！</p>
      <div class="admin-features">
        <div class="feature-card">
          <h3>企业管理</h3>
          <p>管理所有注册企业账户和套餐信息</p>
        </div>
        <div class="feature-card">
          <h3>系统监控</h3>
          <p>监控系统运行状态和服务质量</p>
        </div>
        <div class="feature-card">
          <h3>数据分析</h3>
          <p>查看平台整体运营数据和统计报表</p>
        </div>
      </div>
    </div>

    <!-- 企业用户页面 -->
    <div v-else class="enterprise-content">
      <HeroSection />
      <PricingSection 
        :subscription-status="subscriptionStatus"
        @subscribe="handleSubscribe"
        @unsubscribe="handleUnsubscribe"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import HeroSection from '@/components/HeroSection.vue'
import PricingSection from '@/components/PricingSection.vue'
import { getCompanyInfo, subscribe, unsubscribe } from '@/apis/companyAPI'
import { ElMessage } from 'element-plus'

// 响应式数据
const loading = ref(true)
const isAdmin = ref(false)
const subscriptionStatus = ref(0) // 0:未订阅, 1:已订阅
const companyInfo = ref(null)

// 获取企业信息
const fetchCompanyInfo = async () => {
  try {
    loading.value = true
    const response = await getCompanyInfo()
    
    // 检查响应是否成功
    if (response && response.code === 200 && response.data) {
      companyInfo.value = response.data
      
      // 判断是否为管理员
      isAdmin.value = companyInfo.value.id === 0
      
      // 存储订阅状态到localStorage
      subscriptionStatus.value = companyInfo.value.hasSubscription || 0
      try {
        if (typeof localStorage !== 'undefined') {
          localStorage.setItem('subscriptionStatus', subscriptionStatus.value)
          localStorage.setItem('hasSubscription', subscriptionStatus.value)
          localStorage.setItem('companyInfo', JSON.stringify(companyInfo.value))
          localStorage.setItem('isAdmin', isAdmin.value)
        }
      } catch (error) {
        console.error('保存到localStorage失败:', error)
      }
    } else {
      throw new Error('获取企业信息失败：响应数据格式错误')
    }
  } catch (error) {
    console.error('获取企业信息时发生错误:', error)
    ElMessage.error('获取企业信息失败，请稍后重试')
    
    // 使用localStorage中的缓存数据作为备选
    useCachedData()
  } finally {
    loading.value = false
  }
}

// 使用缓存数据
const useCachedData = () => {
  try {
    if (typeof localStorage !== 'undefined') {
      const cachedCompanyInfo = localStorage.getItem('companyInfo')
      const cachedIsAdmin = localStorage.getItem('isAdmin')
      const cachedSubscriptionStatus = localStorage.getItem('subscriptionStatus')
      
      if (cachedCompanyInfo) {
        companyInfo.value = JSON.parse(cachedCompanyInfo)
        isAdmin.value = cachedIsAdmin === 'true'
        subscriptionStatus.value = parseInt(cachedSubscriptionStatus) || 0
        console.log('使用缓存的企业信息')
      }
    }
  } catch (error) {
    console.error('读取缓存数据失败:', error)
  }
}

// 订阅处理函数
const handleSubscribe = async (data) => {
  try {
    console.log('订阅套餐:', data.plan)
    console.log('订阅状态:', data.hasSubscription)
    
    // 调用后端API进行订阅
    const response = await subscribe({
      plan: data.plan,
      subscriptionDate: new Date().toISOString()
    })
    
    // 更新订阅状态为1（已订阅）
    subscriptionStatus.value = 1
    
    try {
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem('subscriptionStatus', '1')
        localStorage.setItem('hasSubscription', '1')
        
        // 如果companyInfo存在，也更新它
        if (companyInfo.value) {
          companyInfo.value.hasSubscription = 1
          localStorage.setItem('companyInfo', JSON.stringify(companyInfo.value))
        }
      }
    } catch (storageError) {
      console.error('保存订阅状态到localStorage失败:', storageError)
    }
    
    ElMessage.success('订阅成功！您现在可以使用专业版功能了。')
    
    // 订阅成功后刷新页面，确保路由重新渲染
    if (window.refreshSubscriptionPage) {
      setTimeout(() => {
        window.refreshSubscriptionPage();
      }, 500); // 延迟执行，让用户能看到成功提示
    }
  } catch (error) {
    console.error('订阅失败:', error)
    ElMessage.error('订阅失败，请稍后重试')
  }
}

// 取消订阅处理函数
const handleUnsubscribe = async (data) => {
  try {
    console.log('取消订阅，新状态:', data.hasSubscription)
    
    // 调用后端API进行取消订阅
    const response = await unsubscribe()
    
    // 更新订阅状态为0（未订阅）
    subscriptionStatus.value = 0
    
    try {
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem('subscriptionStatus', '0')
        localStorage.setItem('hasSubscription', '0')
        
        // 如果companyInfo存在，也更新它
        if (companyInfo.value) {
          companyInfo.value.hasSubscription = 0
          localStorage.setItem('companyInfo', JSON.stringify(companyInfo.value))
        }
      }
    } catch (storageError) {
      console.error('保存取消订阅状态到localStorage失败:', storageError)
    }
    
    ElMessage.success('已取消订阅，您可以继续使用免费版功能。')
    
    // 取消订阅成功后刷新页面，确保路由重新渲染
    if (window.refreshSubscriptionPage) {
      setTimeout(() => {
        window.refreshSubscriptionPage();
      }, 500); // 延迟执行，让用户能看到成功提示
    }
  } catch (error) {
    console.error('取消订阅失败:', error)
    ElMessage.error('取消订阅失败，请稍后重试')
  }
}

// 组件挂载时获取企业信息
onMounted(() => {
  fetchCompanyInfo()
})
</script>

<style scoped>
.main-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  gap: 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 管理员页面样式 */
.admin-content {
  text-align: center;
  padding: 40px 20px;
}

.admin-content h1 {
  color: #303133;
  margin-bottom: 20px;
  font-size: 2.5em;
}

.admin-content p {
  color: #606266;
  margin-bottom: 40px;
  font-size: 1.2em;
}

.admin-features {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
  max-width: 1200px;
  margin: 0 auto;
}

.feature-card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.feature-card h3 {
  color: #303133;
  margin-bottom: 15px;
  font-size: 1.3em;
}

.feature-card p {
  color: #606266;
  margin: 0;
  font-size: 1em;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-view {
    padding: 10px;
  }
  
  .admin-content h1 {
    font-size: 2em;
  }
  
  .admin-features {
    grid-template-columns: 1fr;
  }
}
</style>